import { showToast } from './../../utils/util'
import QR from 'qrcode-base64'
var app = getApp()

Page({
	data: {
		code: !1,
		time: '00:00:00',
		timer: '',
		showPhoto: false,
		user_ids: 0,
		order_id: 0,
		order_info: {} // 订单信息
	},
	/**
	 * @function 页面加载回调
	 * @param {*} t
	 */
	onLoad: function (t) {
		this.setData({
			user_ids: t.user_ids,
			order_id: t.id
		})

		app.getUrl(this)
		app.getSystem(this)

		this.getOrderInfo(t)
	},
	/**
	 * @function 下拉刷新回调
	 */
	onPullDownRefresh() {
		console.log('下拉刷新')
		this.getOrderInfo(
			{
				id: this.data.order_id,
				user_ids: this.data.user_ids
			},
			() => {
				//停止下拉刷新
				wx.stopPullDownRefresh()
			}
		)
	},

	/**
	 * @function 获取订单详情信息
	 * @param {*} cb 成功回调函数，之前没有封promise，所以这边用callback函数来处理
	 */
	getOrderInfo(query, cb) {
		app.util.request({
			url: 'order/orderInfo',
			data: {
				id: query.id,
				user_id: query.user_ids
			},
			testapi: app.siteInfo.siteroot_web,
			success: res => {
				this.setData({
					order_info: res.data.data
				})
				// 待支付状态下，10分钟倒计时
				if (res.data.data.order_status == 0) {
					const total = this.calculationCountDowntime(res.data.data)
					// 倒计时开始
					this.countdown(total)
				} else if (res.data.data.order_status == 2) {
					// 待入住状态下，获取核销码
					this.getWriteOffCodeImg(query)
				}

				// 因为没有封装promise，所以这边用cb，来处理
				cb && cb()
			}
		})
	},
	/**
	 * @function 计算倒计时时间
	 */
	calculationCountDowntime(res) {
		var currentTime = res.create_time //下单时间戳
		const currsjc = new Date(currentTime).getTime() // 获取当前日期对象并返回其时间戳
		// 将13位时间戳转换成10位时间戳
		var tenTimestamp = Math.floor(currsjc / 1000)

		var futureTime = new Date(tenTimestamp * 1000 + 10 * 60 * 1000)
		var timestamp = new Date(futureTime).getTime()
		var NowTime = new Date().getTime() //获取系统当前时间戳
		var NowTimes = Math.floor(NowTime / 1000)
		var tenDigitTimestamp = Math.floor(timestamp / 1000) //获取订单失效的时间戳，10分钟后时间戳
		console.log('||||', NowTimes <= tenDigitTimestamp, '」』」', tenDigitTimestamp - NowTimes)
		// 当前时间是否在10分钟内，10分钟关闭订单
		return NowTimes <= tenDigitTimestamp ? tenDigitTimestamp - NowTimes : 0 //下单以后剩余的时间
	},
	/**
	 * @function 倒计时函数
	 * @param {*} total 总共剩下多少时间
	 * @param {*} id
	 * @param {*} hb_id
	 * @returns
	 */
	countdown: function (total) {
		if (total <= 0) {
			this.setData({
				time: '00:00:00'
			})
			clearTimeout(this.data.timer)
			return
		}
		this.data.timer = setTimeout(() => {
			this.setData({
				time: this.dateformat(total - 1)
			})
			this.countdown(total - 1)
		}, 1000)
	},
	/**
	 * @function 获取核销码
	 */
	getWriteOffCodeImg(query) {
		const imgData = QR.drawImg(query.id, {
			typeNumber: 4,
			errorCorrectLevel: 'M',
			size: 300
		})
		this.setData({
			bath: imgData
		})
	},
	clickImg: function () {
		wx.setScreenBrightness({
			value: 1
		})
		this.setData({
			showPhoto: true
		})
	},
	clickImgF: function () {
		wx.setScreenBrightness({
			value: 0.5
		})
		this.setData({
			showPhoto: false
		})
		wx.startPullDownRefresh()
	},
	/**
	 * @function 点击下载小程序图片
	 */
	xzClick: function () {
		wx.getFileSystemManager().writeFile({
			filePath: wx.env.USER_DATA_PATH + '/DHG.png',
			data: this.data.bath.slice(22),
			encoding: 'base64',
			success(res) {
				if (res.errMsg == 'writeFile:ok') {
					wx.saveImageToPhotosAlbum({
						filePath: wx.env.USER_DATA_PATH + '/DHG.png',
						success(res) {
							showToast('图片保存成功')
						},
						fail(err) {
							if (
								err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied' ||
								err.errMsg === 'saveImageToPhotosAlbum:fail auth deny' ||
								err.errMsg === 'saveImageToPhotosAlbum:fail authorize no response'
							) {
								wx.showModal({
									title: '提示',
									content: '需要您授权保存相册',
									showCancel: false,
									success: res => {
										wx.openSetting({
											success(res) {
												if (
													settingdata.authSetting[
														'scope.writePhotosAlbum'
													]
												) {
													showToast('获取权限成功,再次点击下载即可保存')
												} else {
													showToast('获取权限失败，将无法保存到相册哦~')
												}
											},
											fail(err) {
												console.log('fail', err)
											},
											complete(res) {
												console.log('finish', res)
											}
										})
									}
								})
							} else if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
								showToast('取消了保存图片')
							} else {
								showToast(err.errMsg)
							}
						}
					})
				} else {
					showToast('图片下载失败')
				}
			},
			fail(e) {
				showToast('图片下载失败')
			}
		})

		setTimeout(function () {
			wx.setScreenBrightness({
				value: 0.5
			})
		}, 1000)
	},
	dateformat: function (micro) {
		var second = Math.floor(micro % 60)
		var min = Math.floor(micro / 60)
		return (
			'00' + ':' + (min < 10 ? '0' + min : min) + ':' + (second < 10 ? '0' + second : second)
		)
	},
	/**
	 * @function 待付款状态下，点击立即支付
	 * @param {*} t
	 */
	confirmPay() {
		wx.showLoading({
			title: '下单中...'
		})
		app.util.request({
			url: 'check/subPay',
			cachetime: '0',
			data: {
				user_id: this.data.user_ids,
				order_id: this.data.order_id
			},
			testapi: app.siteInfo.siteroot_web,
			method: 'POST',
			success: res => {
				if (res.data.code === 0) {
					wx.openEmbeddedMiniProgram({
						appId: res.data.data.appId,
						path: res.data.data.prePayTn,
						envVersion: 'release',
						success: res => {
							// 订阅半屏小程序关闭，返回主体小程序事件
							app.globalData.eventObserver.subscribe('refreshOrderStatus', res => {
								// 如果是从易宝小程序返回，表示小程序支付完成
								if (res.referrerInfo.appId !== app.globalData.payAppId) {
									return
								}
								this.getOrderInfo({
									id: this.data.order_id,
									user_ids: this.data.user_ids
								})
								// 注销订阅
								app.globalData.eventObserver.unSubscribe('refreshOrderStatus')
							})
							that.setData({
								pay_num: 1
							})
						},
						fail: err => {
							showToast('打开支付半屏小程序失败，请先升级微信版本')
						}
					})
				} else {
					wx.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 1000
					})
				}
				wx.hideLoading()
			}
		})
	},
	/**
	 * @function 再订一间
	 * @param {*} t
	 */
	order_more() {
		wx.navigateTo({
			url: '../hotel_list/hotel_info?hotel_id=' + this.data.order_info.seller_id + '&type=1'
		})
	},
	/**
	 * @function 跳转到开发票页面
	 */
	fapiao() {
		wx.navigateTo({
			url:
				'../fapiao/fapiao?order_id=' +
				this.data.order_info.id +
				'&money=' +
				this.data.order_info.total_cost
		})
	},
	/**
	 * @function 未支付时取消订单
	 */
	cancelOrder() {
		wx.showModal({
			title: '温馨提示',
			content: '是否取消订单？',
			success: res => {
				if (res.confirm) {
					console.log('用户点击确定')
					this.confirmCancelOrder()
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			}
		})
	},

	/**
	 * @function 取消订单
	 * @param {*} t
	 */
	confirmCancelOrder() {
		var that = this
		wx.showLoading({
			title: '取消订单中...'
		})
		app.util.request({
			url: 'order/cancelOrder',
			data: {
				user_id: that.data.user_ids,
				id: that.data.order_id
			},
			testapi: app.siteInfo.siteroot_web,
			success: t => {
				this.getOrderInfo({
					id: that.data.order_id,
					user_ids: that.data.user_ids
				})
				wx.hideLoading()
			}
		})
	},
	/**
	 * @function 已经支付的情况下取消订单，需要确认弹框
	 * @param {*} t
	 */
	applyRefund: function (t) {
		wx.showModal({
			title: '温馨提示',
			content: '是否取消订单？',
			success: res => {
				if (res.confirm) {
					console.log('用户点击确定')
					this.confirmRefund(t)
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			}
		})
	},
	/**
	 * @function 支付后确认取消订单
	 */
	confirmRefund() {
		const that = this

		wx.showLoading({
			title: '取消订单中...'
		})
		app.util.request({
			url: 'order/applyRefund',
			data: {
				user_id: that.data.user_ids,
				id: that.data.order_id
			},
			testapi: app.siteInfo.siteroot_web,
			success: t => {
				if (t.data.code == 0) {
					this.getOrderInfo({
						id: this.data.order_id,
						user_ids: this.data.user_ids
					})
					wx.hideLoading()
				} else {
					wx.showToast({
						title: t.data.msg,
						icon: 'none'
					})
				}
			}
		})
	},
	onUnload: function () {
		if (this.data.timer) {
			clearTimeout(this.data.timer)
		}
		wx.setScreenBrightness({
			value: 0.5
		})
	}
})
